package com.next

import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_COMPANY_USER'])
class LeadTeamController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def springSecurityService
    def exportService

    def index(Integer max)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def leadTeamList = LeadTeam.findAll("from LeadTeam where user.username = '${username}' order by lead.modifiedDate desc", [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = LeadTeam.executeQuery("select count(id) from LeadTeam where user.username = '${username}'")

        respond leadTeamList, model: [leadTeamCount: count[0]]
    }

    def show(LeadTeam leadTeam)
    {
        respond leadTeam
    }

    def create()
    {
        def lead = Lead.findById(params['lead'])
        def user = User.findByUsername(springSecurityService?.getPrincipal()?.username)
        def userList = User.list()
        def leadTeams = LeadTeam.findAllByLead(lead)
        leadTeams?.each {
            userList -= it?.user
        }
        respond new LeadTeam(params), model: [userList: userList]
    }

    @Transactional
    def save(LeadTeam leadTeam)
    {
        def userList = User.list()
        def leadTeams = LeadTeam.findAllByLead(leadTeam?.lead)
        leadTeams?.each {
            userList -= it?.user
        }

        if (leadTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (leadTeam.hasErrors())
        {
            //COMMENT THE INFO THEN YOU WILL SEE MIRACLES
            log.info "userList:" + userList

            transactionStatus.setRollbackOnly()
            respond leadTeam.errors, model: [userList: userList], view: 'create'
            return
        }

        leadTeam.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'leadTeam.label', default: 'LeadTeam'), leadTeam.id])
                // redirect leadTeam
                redirect(controller: "lead", action: "show", params: [id: leadTeam?.lead?.id])
            }
            '*' { respond leadTeam, [status: CREATED] }
        }
    }

    def edit(LeadTeam leadTeam)
    {
        respond leadTeam
    }

    @Transactional
    def update(LeadTeam leadTeam)
    {
        if (leadTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (leadTeam.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond leadTeam.errors, view: 'edit'
            return
        }

        leadTeam.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'leadTeam.label', default: 'LeadTeam'), leadTeam.id])
                // redirect leadTeam
                redirect(controller: "lead", action: "show", params: [id: leadTeam?.lead?.id])
            }
            '*' { respond leadTeam, [status: OK] }
        }
    }

    @Transactional
    def delete(LeadTeam leadTeam)
    {

        if (leadTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        leadTeam.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'leadTeam.label', default: 'LeadTeam'), leadTeam.id])
                // redirect action:"index", method:"GET"
                redirect(controller: "lead", action: "show", params: [id: leadTeam?.lead?.id])
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'leadTeam.label', default: 'LeadTeam'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    @Transactional
    def searchLeadTeam()
    {
        def username = springSecurityService?.getPrincipal()?.username
        def ownerFullName = params["ownerFullName"]
        String sql = "from LeadTeam as u where 1 = 1 and u.user.username = '${username}'"
        if (ownerFullName)
        {
            sql += " and u.lead.user.fullName like '%${ownerFullName}%'"
        }

        def company = params['company']
        if (company)
        {
            sql += " and u.lead.company like '%${company}%'"
        }

        String countSql = "select count(u.id) " + sql
        sql += ' order by createdDate desc'

        def list = LeadTeam.findAll(sql, [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = LeadTeam.executeQuery(countSql)

        respond list, model: [leadTeamCount: count[0], params: params], view: 'index'
    }

    def exportLeadTeam()
    {
        def username = springSecurityService?.getPrincipal()?.username
        def ownerFullName = params["ownerFullName"]
        String sql = "from LeadTeam as u where 1 = 1 and u.user.username = '${username}'"
        if (ownerFullName)
        {
            sql += " and u.lead.user.fullName like '%${ownerFullName}%'"
        }

        def company = params['company']
        if (company)
        {
            sql += " and u.lead.company like '%${company}%'"
        }

        String countSql = "select count(u.id) " + sql
        sql += ' order by createdDate desc'

        def list = LeadTeam.findAll(sql)
        def count = LeadTeam.executeQuery(countSql)
        if (params?.f && params.f != "html")
        {
            response.contentType = grailsApplication.config.grails.mime.types[params.f]
            response.setHeader("Content-disposition", "attachment; filename=leadTeam.${params.extension}")
            List fields = ["lead.company", "lead.numberOfEmployees", "lead.industry.name", "lead.website", "lead.address", "lead.rating.name", "lead.status.name", "lead.fullName", "lead.salutation", "lead.title", "lead.email", "lead.cellphone", "lead.phone", "lead.description", "lead.createdDate", "lead.modifiedDate"]
            Map labels = ["lead.company": "公司名称", "lead.numberOfEmployees": "人数", "lead.industry.name": "行业", "lead.website": "网站", "lead.address": "地址", "lead.rating.name": "评级", "lead.status.name": "状态", "lead.fullName": "姓名", "lead.salutation": "称谓", "lead.title": "头衔", "lead.email": "邮件", "lead.cellphone": "手机", "lead.phone": "座机", "lead.description": "线索描述", "lead.createdDate": "创建时间", "lead.modifiedDate": "修改时间"]
            exportService.export(params.f, response.outputStream, list, fields, labels, [:], [:])
        }
    }
}
